﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using SinaWeiboPlugin.Properties;
using Slippor.Common.PluginFramework;
using Slippor.Douban.Radio.Assist;
using Slippor.Douban.Radio.Share;

namespace SinaWeiboPlugin
{
    public class SinaWeiboSharer : ISharer, IHotkeyExcutor
    {
        public const string Key = "新浪微博";

        private readonly TweetBuilder _tweetBuilder;

        private Song _currentSong = Song.DefaultSong;
        public Song CurrentSong
        {
            get { return _currentSong; }
        }

        readonly IPlugin _plugin;
        public IPlugin Plugin
        {
            get { return _plugin; }
        }

        public SinaWeiboSharer(IPlugin plugin)
        {
            _settings.Upgrade();
            _plugin = plugin;
            _tweetBuilder = new TweetBuilder(this);
            FortuneTeller.LastFortuneDate = _settings.FortunedDay;
        }

        public string Name
        {
            get { return Key; }
        }

        private readonly Settings _settings = SinaWeiboConfig.SettingManager.Settings as Settings;

        UploadForm _uploadForm;
        public void Share()
        {
            if (_settings.DirectSend)
            {
                DirectShare();
            }
            else
            {
                if (_uploadForm == null || _uploadForm.IsDisposed)
                {
                    _uploadForm = new UploadForm(_tweetBuilder);
                }
                _uploadForm.Show();
                if (_uploadForm.WindowState == FormWindowState.Minimized)
                {
                    _uploadForm.WindowState = FormWindowState.Normal;
                }
                _uploadForm.Activate();
                _uploadForm.BringToFront();
            }
        }

        public void DirectShare()
        {
            using (var sendWorker = new BackgroundWorker())
            {
                if (PreShare != null)
                {
                    PreShare(this, null);
                }
                sendWorker.DoWork += (senderD, eD) =>
                {
                    _tweetBuilder.Refresh();
                    eD.Result = _tweetBuilder.Upload();
                };
                sendWorker.RunWorkerCompleted += (senderC, eC) =>
                {
                    if (PostShare != null)
                    {
                        PostShare(senderC, eC);
                    }
                };
                sendWorker.RunWorkerAsync();
            }
        }

        public void DirectShareFortune()
        {
            using (var sendWorker = new BackgroundWorker())
            {
                if (PreShare != null)
                {
                    PreShare(this, null);
                }
                sendWorker.DoWork += (senderD, eD) =>
                {
                    _tweetBuilder.Refresh();
                    _tweetBuilder.Message = FortuneTeller.BuildTweet(_currentFortune);
                    eD.Result = _tweetBuilder.Upload();
                };
                sendWorker.RunWorkerCompleted += (senderC, eC) =>
                {
                    if (PostShare != null)
                    {
                        PostShare(senderC, eC);
                    }
                };
                sendWorker.RunWorkerAsync();
            }
        }

        public event EventHandler PreShare;
        public event EventHandler<RunWorkerCompletedEventArgs> PostShare;

        public bool ErrorAlert
        {
            get { return _settings.ErrorAlert; }
        }

        #region ITracker Members
        private bool _autoSharedFav = false;
        private bool _autoSharedFortune = false;
        private Fortune _currentFortune = null;

        public void Track(Song song)
        {
            _currentSong = song;
            _autoSharedFav = false;
            _autoSharedFortune = false;
            if (_settings.EnableFortune && (!_settings.FortuneOnceDay || !FortuneTeller.FortunedToday))
            {
                _currentFortune = FortuneTeller.GetFortune();
                if (_currentFortune != null)
                {
                    _currentFortune.Answer = _currentSong;
                    _settings.FortunedDay = DateTime.Now;
                    _settings.Save();
                }
            }
            else
            {
                _currentFortune = null;
            }
            if (_uploadForm != null && !_uploadForm.IsDisposed)
            {
                if (_settings.AutoUpdate)
                {
                    _uploadForm.UpdateInfo();
                }
                if (_currentFortune != null)
                {
                    _uploadForm.RefreshFortuneList();
                    _uploadForm.Update(_currentFortune);
                }
            }
        }

        public void TrackUpdate(ICommand command, Song song)
        {
            try
            {
                if (song != null)
                {
                    switch (command.Command)
                    {
                        case Command.Other:
                            if (_uploadForm != null && !_uploadForm.IsDisposed)
                            {
                                if (_settings.AutoUpdate)
                                {
                                    _uploadForm.UpdateInfo();
                                }
                                if (_currentFortune != null)
                                {
                                    _uploadForm.RefreshFortuneList();
                                    _uploadForm.Update(_currentFortune);
                                }
                            }
                            if (song.Album != null && _settings.AutoShareFav && song.FaveState == FavState.Fav && !_autoSharedFav)
                            {
                                _autoSharedFav = true;
                                DirectShare();
                            }
                            if ((song.Album != null || !_settings.FortuneWithArtists) && _settings.AutoSendFortune && _currentFortune != null && !_autoSharedFortune)
                            {
                                _autoSharedFortune = true;
                                DirectShareFortune();
                            }
                            break;
                        case Command.Fav:
                            if (song.Album != null && _settings.AutoShareFav && song.FaveState == FavState.Fav && !_autoSharedFav)
                            {
                                _autoSharedFav = true;
                                DirectShare();
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
            }
        }

        public void Clear()
        {
        }

        public void Pause()
        {
        }

        public void Resume()
        {
        }

        public void Stop()
        {
        }
        #endregion

        #region IHotkeyExcutor Members
        public String Hotkey
        {
            get
            {
                return _settings.ShortCutKey;
            }
            set
            {
                _settings.ShortCutKey = value;
            }
        }

        public void Excute()
        {
            Share();
        }
        #endregion
    }
}